import React from 'react';
import {Row,Col, Button, Table, Modal, Upload} from 'antd';
import qs from 'qs';
import BreadcrumbCustom from '../../../BreadcrumbCustom';
import * as Constant from "../../../../common/const";
import * as Request from '../../../../Server/Upgrade';
import {message} from "antd/lib/index";
import RegisterDownloadForm from "./DownloadForm";
import * as config from "../../../../axios/config";
import {AuthA,AuthButton} from '../../../auth/OperationAuth';
import TablePage from "../../../TablePage";
import {getPageParams,downloadExcel,getButtonCol } from '../../../../common/utils';
require('../../../systemManager/customer.css');

let defaultQuery = {page: Constant.DEFAULT_PAGE, size: Constant.DEFAULT_PAGE_SIZE};
const confirm = Modal.confirm;
const success = Modal.success;

class Download extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            pagination: {},
            loading: false,
            title: undefined,
            visible: false,
            downloadInfo: undefined
        };
    }

    componentDidMount() {
        this.fetchData();
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }


    fetchData = (params = defaultQuery) => {
        this.setState({
            loading: true
        });
        Request.downloadsPage(qs.stringify(params)).then(res => {
            if (Constant.REQUEST_SUCCESS == res.code) {
                let data = res.data;
                this.setState({
                    dataSource: data.content,
                    pagination: {...this.state.pagination, total: data.totalSize, current: data.page + 1,pageSize:params.size},
                    loading: false,
                });
            }
        });
    }
    //导入后的回调
    importSuccessFunc = (file) => {
        if (file.code ==  Constant.REQUEST_SUCCESS) {
            if(file.data&&file.data.length>0){
                let rowItem = file.data.map((item)=>{
                    return <Row className='info-row'>
                        {item.serverName}
                    </Row>
                })
                success({
                    title: '导入成功，请检查重复服务器名称',
                    content: rowItem,
                    maskClosable: true,
                    centered: true,
                    // width: 475,
                    style:{
                        textAlign: 'center'
                    },
                })
            }else{
                message.success('导入成功', Constant.AUTO_DISAPPEAR_TIME);
            }
            this.fetchData();
        } else {
            message.error(file.msg, Constant.ERROR_DISAPPEAR_TIME);
        }
    }
    //导出
    export = () => {
        Request.downloadExport().then(res => {
            const { data, headers } = res;
            var blob = new Blob([data],{type:'application/vnd.ms-excel;charset=UTF-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            downloadExcel(blob, '下载服务器表.xlsx', data);
        })
    }
    //新增
    add = () => {
        this.setState({
            title: '添加下载服务器信息',
            visible: true,
            downloadInfo: undefined
        })
    }

    //编辑
    edit = (id) => {
        Request.downloadGetById(id).then(res => {
            if (Constant.REQUEST_SUCCESS == res.code) {
                this.setState({
                    visible: true,
                    downloadInfo: res.data,
                    title: '修改下载服务器信息'
                });
            }
        });
    }
    //删除
    delete = (id) => {
        confirm({
            title: '删除提示',
            content: '确认删除该条信息',
            maskClosable: true,
            okText: '确定',
            okType: 'primary',
            cancelText: '取消',
            onOk: () => {
                Request.downloadDeleteById(qs.stringify({id: id})).then(res => {
                    if (Constant.REQUEST_SUCCESS == res.code) {
                        this.fetchData(getPageParams(this.state.pagination,true));
                        message.success(Constant.DELETE_SUCCESS_TIP, Constant.AUTO_DISAPPEAR_TIME);
                    }
                })
            }
        });
    }
    cancel = (flag = false) => {
        if(typeof flag == 'object'){
            flag = false;
        }
        this.setState({
            visible: false
        });
        flag && this.fetchData(getPageParams(this.state.pagination));
    }
    /* 翻页 */
    handleTableChange = (pagination) => {
        const _this = this;
        const pager = {..._this.state.pagination};
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        _this.setState({
            pagination: pager,
            loading: true
        });
        _this.fetchData(getPageParams(pagination));
    }

    render() {

        const uploaderProps = {
            action: config.DOWNLOAD_IMPORT,
            headers: {
                authorization: 'authorization-text',
            },
            fileList: [],
            onSuccess: this.importSuccessFunc //文件请求完成返回方法
        };

        const columns = [
            {
                title: "主键",
                dataIndex: "id",
                width: '16.66%',
                align: 'center',
            },
            {
                title: "起始IP",
                dataIndex: "startIp",
                width: '16.66%',
                align: 'center'
            },
            {
                title: "结束IP",
                dataIndex: "endIp",
                width: '16.66%',
                align: 'center'
            }, {
                title: "下载地址",
                dataIndex: "downloadAddress",
                width: '16.66%',
                align: 'center'
            },
            {
                title: "服务器名称",
                dataIndex: "serverName",
                width: '16.66%',
                align: 'center'
            },
            {
                title: "操作",
                width: '16.66%',
                align: 'center',
                render: (text, record) =>
                    (
                        <span>
                             <AuthA onClick={this.edit.bind(this, record.id)} permission={'download:save'}
                                    className={'operation-primary'}>编辑</AuthA>
                             <AuthA onClick={this.delete.bind(this, record.id, record.name)} permission={'download:delete'}
                                className={'operation-danger'}>删除</AuthA>
                         </span>
                    )
            }
        ];
        return (
            <div>
                <Row>
                    <BreadcrumbCustom first={'下载服务器表'}/>
                </Row>
                <Row className="button-margin">
                    <Col {...getButtonCol('download:save')} className="button-margin">
                        <AuthButton size={'large'} onClick={this.add} className={'ant-btn-large'} permission={'download:save'}>
                            添加信息
                        </AuthButton>
                    </Col>
                    <Col {...getButtonCol('download:save')} className="button-margin">
                        <Upload {...uploaderProps}>
                            <AuthButton size='large' permission={'download:save'}>
                                批量导入
                            </AuthButton>
                        </Upload>
                    </Col>
                    <Col {...getButtonCol('download:get')} className="button-margin">
                        <AuthButton size={'large'} onClick={this.export} className={'ant-btn-large'} permission={'download:get'}>
                            批量导出
                        </AuthButton>
                    </Col>
                </Row>
                <Row>
                    <TablePage
                        dataSource={this.state.dataSource}
                        columns={columns}
                        rowKey={record => record.id}
                        pagination={this.state.pagination}
                        loading={this.state.loading}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <Row>
                    <Modal
                        title={this.state.title}
                        visible={this.state.visible}
                        footer={null}
                        onCancel={this.cancel}
                        maskClosable={false}
                        destroyOnClose={true}
                        centered={true}
                    >
                        <RegisterDownloadForm
                            cancel={this.cancel}
                            downloadInfo={this.state.downloadInfo}
                        />
                    </Modal>
                </Row>
                <style>{`
                    .ant-confirm-success .ant-confirm-body > .anticon {
                        margin-left: -68%;
                    }
                    .ant-confirm-success .ant-confirm-body .ant-confirm-title {
                        margin-left: 8%; 
                    }
                `}</style>
            </div>
        );
    }
}

export default Download;